<?php

/**
 * JingYao-backend
 *
 * @link     https://gitee.com/wang-zhihui-release/jingyao-backend
 * @apiDocument https://gitee.com/wang-zhihui-release/jingyao-backend/wikis/
 */

namespace App\Services;

use App\Enums\AdminActionTypeEnum;
use App\Models\AdminLog;

class AdminLogService
{
    public function getList(int $page, int $pageSize, array $search)
    {
        $builder = AdminLog::query()->with('user:id,name');
        if (isset($search['user_name'])) {
            $builder->whereHas('user', function ($query) use ($search) {
                $query->where('name', 'like', '%' . $search['user_name'] . '%');
            });
        }
        if (isset($search['start_date'], $search['end_date'])) {
            $builder->where('exec_time', '>=', strtotime($search['start_date']));
            if (strlen($search['end_date']) > 10) {
                $builder->where('exec_time', '<=', strtotime($search['end_date']));
            } else {
                $builder->where('exec_time', '<=', strtotime($search['end_date']) + (24 * 3600));
            }
        }
        if (isset($search['start_date']) && ! isset($search['end_date'])) {
            $builder->where('exec_time', '>=', strtotime($search['start_date']));
        }
        if (! isset($search['start_date']) && isset($search['end_date'])) {
            if (strlen($search['end_date']) > 10) {
                $builder->where('exec_time', '<=', strtotime($search['end_date']));
            } else {
                $builder->where('exec_time', '<=', strtotime($search['end_date']) + (24 * 3600));
            }
        }
        if (! empty($search)) {
            adminLog(new AdminLog(), AdminActionTypeEnum::SELECT, '查询日志');
        }
        $count = $builder->count();
        $list = $builder->skip(($page - 1) * $pageSize)->take($pageSize)->orderByDesc('id')->get();
        return [
            'page' => $page,
            'page_size' => $pageSize,
            'count' => $count,
            'list' => $list,
        ];
    }
}
